import {Component, NgZone, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {mobileValidator, qrcodeValidator} from '../../common/validators';
import {HttpService} from '../../services/http.service';
import {Events, LoadingController, ModalController, NavController, ToastController} from '@ionic/angular';
import {RegistryAgreementComponent} from '../../components/registry-agreement/registry-agreement.component';
import {BasePage} from '../../common/basePage';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {KeyAndSign} from '../../common/key-and-sign.enum';
import {UtilService} from '../../services/util.service';
import {AppConfig} from '../../common/app-config.enum';

/**
 * 注册
 */
@Component({
  selector: 'app-registry',
  templateUrl: './registry.page.html',
  styleUrls: ['./registry.page.scss'],
})
export class RegistryPage extends BasePage implements OnInit {

  public formModel: FormGroup;
  public pwdObj: any = {
    inputType: 'password',
    icon: 'md-eye-off',
    color: 'medium'
  };
  public resendTime = 0;

  public enterpriseScaleOpts = [
    {
      value: 'ES01',
      text: '大型企业'
    }, {
      value: 'ES02',
      text: '中型企业'
    }, {
      value: 'ES03',
      text: '小型企业'
    }, {
      value: 'ES04',
      text: '微型企业'
    }
  ];

  public industryOpts = [
    {
      value: 'A0000',
      text: '农、林、牧、渔业'
    }, {
      value: 'B0000',
      text: '采矿业'
    }, {
      value: 'C0000',
      text: '制造业'
    }, {
      value: 'D0000',
      text: '电力、热力、燃气及水生产和供应业'
    }, {
      value: 'E0000',
      text: '建筑业'
    }, {
      value: 'F0000',
      text: '批发和零售业'
    }, {
      value: 'G0000',
      text: '交通运输、仓储和邮政业'
    }, {
      value: 'H0000',
      text: '住宿和餐饮业'
    }, {
      value: 'I0000',
      text: '信息传输、软件和信息技术服务业'
    }, {
      value: 'J0000',
      text: '金融业'
    }, {
      value: 'K0000',
      text: '房地产业'
    }, {
      value: 'L0000',
      text: '租赁和商务服务业'
    }, {
      value: 'M0000',
      text: '科学研究和技术服务业'
    }, {
      value: 'N0000',
      text: '水利、环境和公共设施管理业'
    }, {
      value: 'O0000',
      text: '居民服务、修理和其他服务业'
    }, {
      value: 'P0000',
      text: '教育'
    }, {
      value: 'Q0000',
      text: '卫生和社会工作'
    }, {
      value: 'R0000',
      text: '文化、体育和娱乐业'
    }, {
      value: 'S0000',
      text: '公共管理、社会保障和社会组织'
    }, {
      value: 'T0000',
      text: '国际组织'
    }, {
      value: 'U0000',
      text: '其他'
    }
  ];

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private fb: FormBuilder,
              private loadingCtrl: LoadingController,
              private modalCtrl: ModalController,
              private zone: NgZone,
              private service$: HttpService,
              private utilService: UtilService,
              private events: Events
  ) {
    super(navCtrl, toastCtrl);
    this.formModel = fb.group({
      userType: [1, [Validators.required]],
      name: [''],
      enterpriseScale: [''],
      industry: [''],
      mobile: [null, [Validators.required, mobileValidator]],
      verificationCode: [null, [Validators.required, qrcodeValidator]],
      password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(20)]],
      invitationCode: [''],
      employee: [false]
    });
  }

  ngOnInit() {
  }

  // 用户类型变化时，增删验证规则
  typeChange($event) {
    if ($event.detail.value === 1) {
      this.formModel.get('name').clearValidators();
      this.formModel.get('name').reset();
      this.formModel.get('enterpriseScale').clearValidators();
      this.formModel.get('enterpriseScale').reset();
      this.formModel.get('industry').clearValidators();
      this.formModel.get('industry').reset();
    } else if ($event.detail.value === 2) {
      this.formModel.get('name').setValidators([Validators.required]);
      this.formModel.get('name').reset();
      this.formModel.get('enterpriseScale').setValidators([Validators.required]);
      this.formModel.get('enterpriseScale').reset();
      this.formModel.get('industry').setValidators([Validators.required]);
      this.formModel.get('industry').reset();
    }
  }

  // 发送验证码
  getVCode() {
    // 需要scene参数： register：注册时；forgetPwd：忘记密码时
    // 发送验证码时会自动校验手机号是否重复
    if (this.formModel.get('mobile').valid) {
      this.service$.doRequest(UrlAndOPT.auth_getScene, {mobile: this.formModel.get('mobile').value, scene: 'register'})
        .subscribe(obj => {
          if (obj) {
            this.showToast(obj['msg']).catch(() => {
            });
            this.resendTime = AppConfig.RESEND_TIME;
            const timer = setInterval(() => {
              this.resendTime--;
              if (this.resendTime === 0) {
                clearInterval(timer);
              }
            }, 1000);
          }
        });
    } else {
      const msg = this.formModel.getError('required', ['mobile']) ? '手机号不能为空' : '手机号有误，请重新输入';
      this.showToast(msg);
    }
  }

  // 执行注册
  async doRegistry() {
    if (this.formModel.valid) {
      const loading = await this.loadingCtrl.create({
        message: '注册中'
      });
      loading.present();
      // 对password加密
      const password = this.utilService.encryptByDES(this.formModel.get('password').value, KeyAndSign.DES_KEY);
      this.service$.doRequest(UrlAndOPT.auth_registry, {...this.formModel.value, password: password})
        .subscribe(async obj => {
          await loading.dismiss();
          if (obj) {
            await this.showToast('恭喜您，注册成功');
            this.events.publish(AppConfig.TOPIC_MOBILE, {mobile: this.formModel.get('mobile').value});
            await this.goBack();
          }
        });
    } else {
      await this.showToast('请完善信息');
    }
  }

  // 切换显示密码
  showPassword() {
    const isText = this.pwdObj.inputType === 'text';
    this.pwdObj = {
      inputType: isText ? 'password' : 'text',
      icon: isText ? 'md-eye-off' : 'md-eye',
      color: isText ? 'medium' : 'tertiary'
    };
  }

  // 打开注册协议
  async openAgreement() {
    const modal = await this.modalCtrl.create({
      component: RegistryAgreementComponent,
      componentProps: {
        title: '用户注册协议',
        OPT: UrlAndOPT.auth_registryAgreement
      }
    });
    return await modal.present();
  }

}
